package cn.jetpiece.cloud.dict.app.modular.dict.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.core.page.PageFactory;
import cn.jetpiece.cloud.dict.app.modular.dict.entity.Dict;
import cn.jetpiece.cloud.dict.app.modular.dict.entity.DictItem;
import cn.jetpiece.cloud.dict.app.modular.dict.mapper.DictItemMapper;
import cn.jetpiece.cloud.dict.app.modular.dict.mapper.DictMapper;
import cn.jetpiece.cloud.dict.app.modular.dict.service.IDictService;
import cn.jetpiece.cloud.model.contants.CommonConstant;
import cn.jetpiece.cloud.model.model.DictModel;
import cn.jetpiece.cloud.model.model.DictModelMany;
import cn.jetpiece.cloud.model.model.TableDictQuery;
import cn.jetpiece.cloud.model.model.TreeSelectModel;
import cn.jetpiece.cloud.redis.contants.CacheConstant;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hancp
 * @version 1.0
 * @description: 字典服务实现类
 * @date 2021-11-08 10:15:39
 */
@Service
@Slf4j
@Primary
@DS("hcwl_auth")
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements IDictService {

    @Autowired
    private DictMapper sysDictMapper;
    @Autowired
    private DictItemMapper sysDictItemMapper;

    /**
     * 通过查询指定code 获取字典
     *
     * @param code
     * @return
     */
    @Override
    @Cacheable(value = CacheConstant.SYS_DICT_CACHE, key = "#code")
    public List<DictModel> queryDictItemsByCode(String code) {
        log.debug("无缓存dictCache的时候调用这里！");
        return sysDictMapper.queryDictItemsByCode(code);
    }

    @Override
    public Map<String, List<DictModel>> queryAllDictItems() {
        Map<String, List<DictModel>> res = new HashMap<>();
        List<Dict> ls = sysDictMapper.selectList(null);
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictItem::getStatus, CommonConstant.STATUS_1);
        queryWrapper.orderByAsc(DictItem::getSortOrder);
        List<DictItem> sysDictItemList = sysDictItemMapper.selectList(queryWrapper);

        for (Dict d : ls) {
            List<DictModel> dictModelList = sysDictItemList.stream().filter(s -> d.getId().equals(s.getDictId())).map(item -> {
                DictModel dictModel = new DictModel();
                dictModel.setText(item.getItemText());
                dictModel.setValue(item.getItemValue() + "");
                return dictModel;
            }).collect(Collectors.toList());
            res.put(d.getDictCode(), dictModelList);
        }
        log.debug("-------登录加载系统字典-----" + res.toString());
        return res;
    }

    /**
     * 通过查询指定code 获取字典值text
     *
     * @param code
     * @param key
     * @return
     */

    @Override
    @Cacheable(value = CacheConstant.SYS_DICT_CACHE, key = "#code+':'+#key", unless = "#result == null")
    public String queryDictTextByKey(String code, String key) {
        log.debug("无缓存dictText的时候调用这里！");
        return sysDictMapper.queryDictTextByKey(code, key);
    }

    /**
     * 通过查询指定table的 text code 获取字典
     * dictTableCache采用redis缓存有效期10分钟
     *
     * @param table
     * @param text
     * @param code
     * @return
     */
    @Override
    //@Cacheable(value = CacheConstant.SYS_DICT_TABLE_CACHE)
    public List<DictModel> queryTableDictItemsByCode(String table, String text, String code) {
        log.debug("无缓存dictTableList的时候调用这里！");
        return sysDictMapper.queryTableDictItemsByCode(table, text, code);
    }

    @Override
    public List<DictModel> queryTableDictItemsByCodeAndFilter(String table, String text, String code, String filterSql) {
        log.debug("无缓存dictTableList的时候调用这里！");
        return sysDictMapper.queryTableDictItemsByCodeAndFilter(table, text, code, filterSql);
    }

    /**
     * 通过查询指定table的 text code 获取字典值text
     * dictTableCache采用redis缓存有效期10分钟
     *
     * @param table
     * @param text
     * @param code
     * @param key
     * @return
     */
    @Override
    @Cacheable(value = CacheConstant.SYS_DICT_TABLE_CACHE)
    public String queryTableDictTextByKey(String table, String text, String code, String key) {
        log.debug("无缓存dictTable的时候调用这里！");
        return sysDictMapper.queryTableDictTextByKey(table, text, code, key);
    }

    /**
     * 通过查询指定table的 text code 获取字典，包含text和value
     * dictTableCache采用redis缓存有效期10分钟
     *
     * @param table
     * @param text
     * @param code
     * @param keys  (逗号分隔)
     * @return
     */
    @Override
    //update-begin--Author:lvdandan  Date:20201204 for：JT-36【online】树形列表bug修改后，还是显示原来值 暂时去掉缓存
    //@Cacheable(value = CacheConstant.SYS_DICT_TABLE_BY_KEYS_CACHE)
    //update-end--Author:lvdandan  Date:20201204 for：JT-36【online】树形列表bug修改后，还是显示原来值 暂时去掉缓存
    public List<String> queryTableDictByKeys(String table, String text, String code, String keys) {
        if (StrUtil.isEmpty(keys)) {
            return null;
        }
        String[] keyArray = keys.split(",");
        List<DictModel> dicts = sysDictMapper.queryTableDictByKeys(table, text, code, keyArray);
        List<String> texts = new ArrayList<>(dicts.size());
        // 查询出来的顺序可能是乱的，需要排个序
        for (String key : keyArray) {
            for (DictModel dict : dicts) {
                if (key.equals(dict.getValue())) {
                    texts.add(dict.getText());
                    break;
                }
            }
        }
        return texts;
    }

    /**
     * 根据字典类型id删除关联表中其对应的数据
     */
    @Override
    public boolean deleteByDictId(Dict sysDict) {
        sysDict.setDelFlag(1);
        return this.updateById(sysDict);
    }

    @Override
    @Transactional
    public Integer saveMain(Dict sysDict, List<DictItem> sysDictItemList) {
        int insert = 0;
        try {
            insert = sysDictMapper.insert(sysDict);
            if (sysDictItemList != null) {
                for (DictItem entity : sysDictItemList) {
                    entity.setDictId(sysDict.getId());
                    entity.setStatus(1);
                    sysDictItemMapper.insert(entity);
                }
            }
        } catch (Exception e) {
            return insert;
        }
        return insert;
    }

    @Override
    public List<DictModel> queryAllDepartBackDictModel() {
        return baseMapper.queryAllDepartBackDictModel();
    }

    @Override
    public List<DictModel> queryAllUserBackDictModel() {
        return baseMapper.queryAllUserBackDictModel();
    }

    @Override
    public List<DictModel> queryTableDictItems(String table, String text, String code, String keyword) {
        return baseMapper.queryTableDictItems(table, text, code, "%" + keyword + "%");
    }

    @Override
    public List<DictModel> queryLittleTableDictItems(String table, String text, String code, String keyword, int pageSize) {
        Page<DictModel> page = new Page<>(1, pageSize);
        IPage<DictModel> pageList = baseMapper.queryTableDictItems(page, table, text, code, "%" + keyword + "%");
        return pageList.getRecords();
    }

    @Override
    public List<TreeSelectModel> queryTreeList(Map<String, String> query, String table, String text, String code, String pidField, String pid, String hasChildField) {
        return baseMapper.queryTreeList(query, table, text, code, pidField, pid, hasChildField);
    }

    @Override
    public void deleteOneDictPhysically(String id) {
        this.baseMapper.deleteOneById(id);
        this.sysDictItemMapper.delete(new LambdaQueryWrapper<DictItem>().eq(DictItem::getDictId, id));
    }

    @Override
    public void updateDictDelFlag(int delFlag, String id) {
        baseMapper.updateDictDelFlag(delFlag, id);
    }

    @Override
    public List<Dict> queryDeleteList() {
        return baseMapper.queryDeleteList();
    }

    @Override
    public List<DictModel> queryDictTablePageList(TableDictQuery query) {
        Page page = PageFactory.defaultPage();
        Page<DictModel> pageList = baseMapper.queryDictTablePageList(page, query);
        return pageList.getRecords();
    }

    /**
     *  根据多个字典code查询多个字典项
     * @param dictCodeList
     * @return key = dictCode ； value=对应的字典项
     */
    @Override
    public Map<String, List<DictModel>> queryDictItemsByCodeList(List<String> dictCodeList) {
        List<DictModelMany> list = baseMapper.queryDictItemsByCodeList(dictCodeList);
        Map<String, List<DictModel>> dictMap = new HashMap<>();
        for (DictModelMany dict : list) {
            List<DictModel> dictItemList = dictMap.computeIfAbsent(dict.getDictCode(), i -> new ArrayList<>());
            dict.setDictCode(null);
            dictItemList.add(new DictModel(dict.getValue(), dict.getText()));
        }
        return dictMap;
    }

    @Override
    public List<DictModel> loadDict(String dictCode, String keyword, Integer pageSize) {
        if (dictCode.contains(",")) {
            //update-begin-author:taoyan date:20210329 for: 下拉搜索不支持表名后加查询条件
            String[] params = dictCode.split(",");
            String condition = null;
            if (params.length != 3 && params.length != 4) {
                // 字典Code格式不正确
                return null;
            } else if (params.length == 4) {
                condition = params[3];
            }
            List<DictModel> ls;
            if (pageSize != null) {
                ls = this.queryLittleTableDictItems(params[0], params[1], params[2], condition, keyword, pageSize);
            } else {
                ls = this.queryAllTableDictItems(params[0], params[1], params[2], condition, keyword);
            }
            //update-end-author:taoyan date:20210329 for: 下拉搜索不支持表名后加查询条件
            return ls;
        } else {
            // 字典Code格式不正确
            return null;
        }
    }

    @Override
    public List<DictModel> queryAllTableDictItems(String table, String text, String code, String condition, String keyword) {
        String filterSql = getFilterSql(table, text, code, condition, keyword);
        List<DictModel> ls = baseMapper.queryAllTableDictItems(table, text, code, filterSql);
        return ls;
    }

    @Override
    public List<DictModel> queryLittleTableDictItems(String table, String text, String code, String condition, String keyword, int pageSize) {
        Page<DictModel> page = new Page<DictModel>(1, pageSize);
        page.setSearchCount(false);
        String filterSql = getFilterSql(table, text, code, condition, keyword);
        IPage<DictModel> pageList = baseMapper.queryTableDictWithFilter(page, table, text, code, filterSql);
        return pageList.getRecords();
    }

    /**
     * 获取条件语句
     * @param text
     * @param code
     * @param condition
     * @param keyword
     * @return
     */
    private String getFilterSql(String table, String text, String code, String condition, String keyword){
        String keywordSql = null, filterSql = "", sql_where = " where ";
        // update-begin-author:sunjianlei date:20220112 for: 【JTC-631】判断如果 table 携带了 where 条件，那么就使用 and 查询，防止报错
        if (table.toLowerCase().contains(" where ")) {
            sql_where = " and ";
        }
        // update-end-author:sunjianlei date:20220112 for: 【JTC-631】判断如果 table 携带了 where 条件，那么就使用 and 查询，防止报错
        if(StrUtil.isNotEmpty(keyword)){
            // 判断是否是多选
            if (keyword.contains(",")) {
                //update-begin--author:scott--date:20220105--for：JTC-529【表单设计器】 编辑页面报错，in参数采用双引号导致 ----
                String inKeywords = "'" + String.join("','", keyword.split(",")) + "'";
                //update-end--author:scott--date:20220105--for：JTC-529【表单设计器】 编辑页面报错，in参数采用双引号导致----
                keywordSql = "(" + text + " in (" + inKeywords + ") or " + code + " in (" + inKeywords + "))";
            } else {
                keywordSql = "("+text + " like '%"+keyword+"%' or "+ code + " like '%"+keyword+"%')";
            }
        }
        if(StrUtil.isNotEmpty(condition) && StrUtil.isNotEmpty(keywordSql)){
            filterSql+= sql_where + condition + " and " + keywordSql;
        }else if(StrUtil.isNotEmpty(condition)){
            filterSql+= sql_where + condition;
        }else if(StrUtil.isNotEmpty(keywordSql)){
            filterSql+= sql_where + keywordSql;
        }
        return filterSql;
    }

}
